<template>
  <div class="msg-container q-ma-md">
    <div class="text-h6">我的订阅</div>
    <div class="row justify-end q-my-md">
      <q-btn @click="openChannel()" color="secondary">我的通道</q-btn>
      <q-btn @click="handleClick()" color="secondary">新增</q-btn>
    </div>
    <q-table
        :data="subscribes"
        :columns="columns"
        table-header-class="bg-green10"
        :table-colspan="pageSize"
        v-model:pagination="pagination"
        row-key="_id"
        separator="cell"
        :loading="isLoading">
      <template v-slot:body-cell-platform="props">
        <q-td :props="props">
          {{ handleDisplay(props.row.platform, 'platform') }}
        </q-td>
      </template>
      <template v-slot:body-cell-type="props">
        <q-td :props="props">
          {{ handleDisplay(props.row.type, 'type') }}
        </q-td>
      </template>
      <template v-slot:body-cell-status="props">
        <q-td :props="props">
          {{ handleDisplay(props.row.status, 'status') }}
        </q-td>
      </template>
      <!-- <template v-slot:body-cell-rule="props">
        <q-td :props="props">
          <div v-if="props.row.rule.year!==null">
            在 {{ props.row.rule.year }} 年
          </div>
          <div v-if="props.row.rule.date!==null">
            每月第 {{ props.row.rule.date }} 天
          </div>
          <div v-if="props.row.rule.dayOfWeek!==null">
            每周第 {{ props.row.rule.dayOfWeek }} 天
          </div>
          <div v-if="props.row.rule.hour!==null">
            每天第 {{ props.row.rule.hour }} 小时
          </div>
          <div v-if="props.row.rule.minute!==null">
            每小时第 {{ props.row.rule.minute }} 分钟
          </div>
          <div v-if="props.row.rule.second!==null">
            每分钟第 <span></span>{{ props.row.rule.second }} 秒
          </div>
        </q-td>
      </template> -->
      <template v-slot:body-cell-opt="props">
        <q-td :props="props">
          <q-btn class="q-mx-sm" @click="handleDelete(props.row)" color="red">删除</q-btn>
          <q-btn class="q-mx-sm" @click="handlePause(props.row)"
                 :color="props.row.status === 1 ? 'amber' : 'secondary'">{{ props.row.status === 1 ? '停用' : '启用' }}
          </q-btn>
          <q-btn class="q-mx-sm" @click="handleClick(props.row)" color="primary">编辑</q-btn>
        </q-td>
      </template>
    </q-table>
    <q-dialog class="dialog" v-model="dialogVisible">
      <q-card class="q-pa-sm" style="width: 800px; max-width: 800px; max-height: 500px;">
        <div class="row">
          <q-card-section class="col-3 scroll channel-list">
            <div class="text-subtitle2 q-my-md">选择热榜</div>
            <q-option-group
                :options="hubs"
                type="checkbox"
                v-model="form.hubIds"
                color="secondary"
            />
          </q-card-section>
          <!-- <q-card-section class="col-9">
            <div class="row justify-between">
              <q-checkbox dense class="" color="secondary" v-model="form.ruleValid.year" @input="form.rule.year=null"/>
              <q-input class="col-5" label="年份" type="number" dense hint="不设置代表全年"
                      v-model.number="form.rule.year"
                      :disable="!form.ruleValid.year"
                      :rules="[ val => (val <= 2030 && val >= 2021) || !val  || '年份需要在 2021-2030 之间' ]"
              ></q-input>
              <q-checkbox dense color="secondary" v-model="form.ruleValid.date" @input="form.rule.date=null"/>
              <q-input class="col-5" label="每月第几天" type="number" dense hint="不设置代表全月"
                      v-model.number="form.rule.date"
                      :disable="!form.ruleValid.date"
                      :rules="[ val => (val <= 31 && val >= 1) || !val  || '天数需要在 1-31 之间' ]"
              ></q-input>
            </div>
            <div class="row q-my-md">
              <q-field label="每周第几天" class="justify-between" stack-label>
                <template v-slot:control>
                  <q-checkbox dense indeterminate-value="partial" v-model="checkAll" label="全选" color="teal"
                              @input="handleCheckAllChange"/>
                  <q-option-group dense
                      v-model="form.rule.dayOfWeek" :options="qDays" @input="handleCheckedDayChange"
                      type="checkbox" color="secondary" inline
                  />
                </template>
              </q-field>
            </div>
            <div class="row q-my-md justify-between">
              <q-checkbox dense color="secondary" v-model="form.ruleValid.hour" @input="form.rule.hour=null"/>
              <q-input class="col-3" label="每天第几小时" type="number" dense
                      v-model.number="form.rule.hour"
                      :disable="!form.ruleValid.hour"
                      :rules="[ val => (val <= 23 && val >= 0) || !val  || '小时需要在 0-23 之间' ]"
              ></q-input>
              <q-checkbox dense color="secondary" v-model="form.ruleValid.minute" @input="form.rule.minute=null"/>
              <q-input class="col-3" label="每小时第几分钟" type="number" dense
                      v-model.number="form.rule.minute"
                      :disable="!form.ruleValid.minute"
                      :rules="[ val => (val <= 59 && val >= 0) || !val  || '分钟需要在 0-59 之间' ]"
              ></q-input>
              <q-checkbox dense color="secondary" v-model="form.ruleValid.second" @input="form.rule.second=null"/>
              <q-input class="col-3" label="每分钟第几秒" type="number" dense
                      v-model.number="form.rule.second"
                      :disable="!form.ruleValid.second"
                      :rules="[ val => (val <= 59 && val >= 0) || !val  || '秒数需要在 0-59 之间' ]"
              ></q-input>
            </div>
          </q-card-section> -->
          <q-card-section class="col-9">
            <q-input class="col-5" label="cron表达式" type="textarea" dense hint=" 秒 分 时 日 月 周几"
                     v-model="form.rules"
            ></q-input>
            <div>回车多个规则</div>
            <div>
              秒：0-59
              分：0-59
              时：0-23
              天：1-31
              月：1-12
              周几：1-7
            </div>
            <div>*全部值；/每隔步长；,多个值；-连续值</div>
            <div>每隔20分钟：* /20 * * * *</div>
            <div>每隔1小时</div>
            <div>每小时0分</div>
            <div>每天9点-12点的第5分钟</div>
            <div>每周二、五</div>
            <div>每月1号</div>
            <div class="text-subtitle2 q-my-md">选择发送通道</div>
            <q-option-group
                :options="channels"
                type="checkbox"
                v-model="form.channelIds"
                color="secondary"
            />
            <q-input type="textarea" dense label="备注" v-model="form.description" placeholder="请输入"></q-input>
          </q-card-section>
        </div>
        <q-separator></q-separator>
        <div class="text-right q-my-md">
          <q-btn class="q-ml-md" @click="dialogVisible = false">取 消</q-btn>
          <q-btn class="q-ml-md" type="primary" @click="submit()" :loading="isLoading">确 定</q-btn>
        </div>
      </q-card>
    </q-dialog>
  </div>
</template>
<script>
import { defineComponent } from 'vue'
import AppActivityMixin from 'src/mixins/app-activity'
import 'highlight.js/styles/monokai-sublime.css'
import 'highlight.js/styles/base16/monokai.css'
import iTop from 'src/api/km/top'
import iMessage from 'src/api/msg/msg'

const defaultForm = {
  _id: '',
  name: '',
  description: '',
  channelId: '',
  hubIds: [],
  channelIds: [],
  type: 1,
  rules: [''],
  rule: {
    second: 0,
    minute: 0,
    hour: 8,
    date: null,
    year: null,
    dayOfWeek: []
  },
  ruleValid: {
    second: true,
    minute: true,
    hour: true,
    date: false,
    year: false
  },
  status: null,
  createUserId: '',
  updateUserId: '',
  createdAt: '',
  updatedAt: '',
  deletedAt: ''
}
const copy = (obj) => JSON.parse(JSON.stringify(obj))

export default defineComponent({
  mixins: [AppActivityMixin],
  components: {},
  data () {
    return {
      dialogVisible: false,
      isLoading: false,
      checkAll: false,
      subscribes: [],
      channels: [],
      hubs: [],
      form: copy(defaultForm),
      qDays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'].map((e, index) => ({
        label: e,
        value: index === 6 ? 0 : index + 1
      })),
      columns: [
        {
          name: 'type',
          label: '类型',
          field: 'type',
          sortable: true,
          align: 'left'
        },
        {
          name: 'icon',
          label: '图标',
          field: 'icon',
          sortable: true,
          align: 'left'
        },
        {
          name: 'name',
          label: '名称',
          field: 'name',
          sortable: true,
          align: 'left'
        },
        {
          name: 'channelName',
          label: '通道名称',
          field: 'channelName',
          sortable: true,
          align: 'left'
        },
        {
          name: 'platform',
          label: '平台',
          field: 'platform',
          sortable: true,
          align: 'left'
        },
        {
          name: 'channeltype',
          label: '方式',
          field: 'channeltype',
          sortable: true,
          align: 'left'
        },
        {
          name: 'rules',
          label: '消息频率',
          field: 'rules',
          sortable: true,
          align: 'left'
        },
        {
          name: 'description',
          label: '备注',
          field: 'description',
          sortable: true,
          align: 'left'
        },
        {
          name: 'updatedAt',
          label: '更新时间',
          field: 'updatedAt',
          sortable: true,
          align: 'left'
        },
        {
          name: 'opt',
          label: '操作',
          sortable: true,
          align: 'middle'
        }
      ],
      pagination: {
        page: 1,
        rowsPerPage: 10,
        sortBy: 'utime',
        descending: true
      },
      pageNo: 1,
      pageSize: 50
    }
  },
  watch: {},
  async mounted () {
    this.initList()
  },
  methods: {
    async initList () {
      const subscribes = await iTop.getListUser()
      subscribes.forEach(e => {
        e.channelName = ''
        e.channels.forEach(c => {
          e.channelName += (c.name + ';')
        })
        if (e.type === 1) {
          e.name = ''
          e.hubs.forEach(c => {
            e.name += (c.name + ';')
          })
        }
        e.rules = e.rules.join('\n')
        // e.ruleValid = {
        //   second: this.isValid(e.rule.second),
        //   minute: this.isValid(e.rule.minute),
        //   hour: this.isValid(e.rule.hour),
        //   date: this.isValid(e.rule.date),
        //   year: this.isValid(e.rule.year)
        // }
      })
      this.subscribes = subscribes
    },
    async initHubs () {
      const hubs = await iTop.getListPub()
      hubs.forEach(e => {
        e.label = e.platform + '-' + e.col
        e.value = e._id
      })
      this.hubs = hubs
    },
    async initChannels () {
      const channels = await iMessage.getList()
      channels.forEach(e => {
        e.label = e.name
        e.value = e._id
      })
      this.channels = channels
    },
    async submit () {
      const subscribe = copy(this.form)
      subscribe.rules = subscribe.rules.split('\n').filter(i => i !== '')
      subscribe.rules.forEach(e => {
        const r = e.replace('  ', ' ')
        console.log(r)
        if (r.split(' ').length !== 5) {
          this.$q.notify({
            icon: '',
            message: '表达式错误 ' + e,
            color: 'warning',
            position: 'top',
            timeout: 2000
          })
          e = r
          return false
        }
      })
      try {
        this.isLoading = true
        if (this.form._id) {
          await iTop.update(subscribe)
        } else {
          await iTop.create(subscribe)
        }
      } catch (err) {
        this.$notify.error(err)
      } finally {
        this.isLoading = false
      }
      this.dialogVisible = false
      await this.initList()
    },
    handleClick (subscribe) {
      this.initHubs()
      this.initChannels()
      if (subscribe) {
        console.log('subscribe', subscribe)
        this.form = copy(subscribe)
      } else {
        this.form = copy(defaultForm)
      }
      this.dialogVisible = true
    },
    handleDelete (subscribe) {
      this.$q.dialog({
        title: '删除确认',
        message: '确认是否要删除？',
        cancel: true,
        persistent: true
      }).onOk(async () => {
        await iTop.delete({
          id: subscribe._id
        })
        await this.initList()
      })
    },
    async handlePause (subscribe) {
      let status = subscribe.status
      if (status === 2) {
        status = 1
      } else {
        status = 2
      }
      await iTop.pause({
        id: subscribe._id,
        status: status
      })
      await this.initList()
    },
    async openChannel () {
      const { href } = this.$router.resolve({ path: '/msg' })
      window.open(href, '_blank')
    },
    isValid (value) {
      return (value !== undefined) && (value !== null)
    },
    handleCheckAllChange (val) {
      this.form.rule.dayOfWeek = val ? [0, 1, 2, 3, 4, 5, 6] : []
    },
    handleCheckedDayChange () {
      const checkedCount = (this.form.rule.dayOfWeek || []).length
      if (checkedCount > 0 && checkedCount < 7) {
        this.checkAll = 'partial'
        return
      }
      if (checkedCount === 7) {
        this.checkAll = true
        return
      }
      this.checkAll = false
    }
  },
  filters: {
    handleDisplay: function (value, field) {
      const enums = {
        platform: {
          1: '企业微信',
          2: '钉钉',
          3: '飞书',
          4: '微信'
        },
        channleType: {
          1: '群机器人',
          2: '应用机器人'
        },
        type: {
          1: '公共资源',
          2: '自建资源'
        },
        status: {
          1: '已启用',
          2: '未启用'
        }
      }
      return enums[field][value]
    }
  }
})
</script>

<style lang="scss">
.msg-container {

}

.text-h6 {

}
</style>
